package com.beiing.tianshuai.tianshuai.widget;

import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.WebView;

import com.beiing.tianshuai.tianshuai.activity.ShowImageFromWebActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by magikliu on 2017/9/18.
 */

public class ShowImageWebView extends WebView {

    private List<String> listImgSrc = new ArrayList<>();
    private List<String> listImgUrl = new ArrayList<>();
    private static final String IMAGE_URL_TAG = "src=\"?(.*?)(\"|>|\\s+)";
    private static final String IMAGE_URL_CONTENT = "http:\"?(.*?)(\"|>|\\s+)";

    private String url;
    private Context context;

    public ShowImageWebView(Context context) {
        super(context);
        init(context);
    }

    public ShowImageWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ShowImageWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context){
        this.context = context;

        this.getSettings().setJavaScriptEnabled(true);
        this.getSettings().setDefaultTextEncodingName("UTF-8");

        //载入js
        this.addJavascriptInterface(new MyJavascriptInterface(context), "imageListener");
        //获取 html
        this.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");
    }

    public void parseHTML(WebView view){
        view.loadUrl("javascript:window.local_obj.showSource('<head>'+"
                + "document.getElementsByTagName('html')[0].innerHTML+'</head>');");
    }

    public void setImageClickListener(){
        // 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，函数的功能是在图片点击的时候调用本地java接口并传递url过去
        this.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "    objs[i].onclick=function()  " +
                "    {  "
                + "        window.imageListener.startShowImageActivity(this.src);  " +
                "    }  " +
                "}" +
                "})()");
    }

    private class MyJavascriptInterface{
        private Context context;

        public MyJavascriptInterface(Context context) {
            this.context = context;
        }

        /**
         * 点击图片启动新的 ShowImageFromWebActivity，并传入点击图片对应的 url 和页面所有图片
         * 对应的 url
         *
         * @param url 点击图片对应的 url
         */
        @android.webkit.JavascriptInterface
        public void startShowImageActivity(String url) {
            Intent intent = new Intent();
            intent.putExtra("imageUrl", url);
            intent.putStringArrayListExtra("imageUrlAll", (ArrayList<String>) listImgSrc);
            intent.setClass(context, ShowImageFromWebActivity.class);

            Log.i("图片路径:", url);
            Log.i("图片路径全：", listImgSrc.toString());
            context.startActivity(intent);
        }
    }

    private class InJavaScriptLocalObj {
        /**
         * 获取要解析 WebView 加载对应的 Html 文本
         *
         * @param html WebView 加载对应的 Html 文本
         */
        @android.webkit.JavascriptInterface
        public void showSource(String html) {
            //从 Html 文件中提取页面所有图片对应的地址对象
            getAllImageUrlFromHtml(html);
        }
    }

    /***
     * 获取页面所有图片对应的地址对象
     *
     * @param html WebView 加载的 html 文本
     * @return
     */
    private List<String> getAllImageUrlFromHtml(String html) {
        Matcher matcher = Pattern.compile(IMAGE_URL_TAG).matcher(html);
//        List<String> listImgUrl = new ArrayList<String>();
        while (matcher.find()) {
            listImgUrl.add(matcher.group());
        }
        //从图片对应的地址对象中解析出 src 标签对应的内容
        getAllImageUrlFormSrcObject(listImgUrl);
        return listImgUrl;
    }

    /***
     * 从图片对应的地址对象中解析出 src 标签对应的内容,即 url
     */
    private List<String> getAllImageUrlFormSrcObject(List<String> listImageUrl) {
        for (String image : listImageUrl) {
//            Matcher matcher = Pattern.compile(IMAGE_URL_CONTENT).matcher(image);
//            while (matcher.find()) {
//                listImgSrc.add(matcher.group().substring(0, matcher.group().length() - 1));
//            }
            if (image.contains("http://www.tianshuai.com.cn")){
                listImgSrc.add(image.substring(5, image.length() - 1));
            } else {
                listImgSrc.add("http://www.tianshuai.com.cn" + image.substring(5, image.length() - 1));
            }
        }
        return listImgSrc;
    }
}
